package first.endtoend

import grails.converters.JSON
import org.springframework.dao.DataIntegrityViolationException

class LocalityController
{

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def scaffold = true
    Level levelRegion = Level.findByName("Region")
    Level levelState = Level.findByName("State")
    Level levelDivision = Level.findByName("Division")
    Level levelVillage = Level.findByName("Village")

    def getAllLocalitiesNames()
    {

        def localities = Locality.list()

        def response = []

        localities.each {
            response << "${it.name}"
        }

        render response as JSON
    }


    def populate()
    {

        Locality localityCountry = Locality.findByName("INDIA")
        localityCountry.children = new ArrayList<Locality>()
        Locality localityRegion

        Locality localityDivision
        Locality localityVillage
        for (int i = 0; i < 5; i++)
        {
            localityRegion = new Locality(level: levelRegion, name: generateName(5)).save(flush: true)
            if (localityCountry)
            {
                localityCountry.children.add(localityRegion)
                localityRegion.localityParent = localityCountry
                populateRegion(localityRegion)
            } else
            {
                println("no country india found")
            }
        }
        flash.message = message(code: 'default.populate.message')

        redirect(action: "list", params: params)
    }

    def populateRegion(Locality aRegion)
    {
        aRegion.children = new ArrayList<Locality>()
        Locality localityState
        for (int i = 0; i < 2; i++)
        {
            localityState = new Locality(level: levelState, name: generateName(5)).save(flush: true)
            aRegion.children.add(localityState)
            localityState.localityParent = aRegion
            populateState(localityState)
        }
    }

    def populateState(Locality aState)
    {
        aState.children = new ArrayList<Locality>()
        Locality localityDivision
        for (int i = 0; i < 2; i++)
        {
            localityDivision = new Locality(level: levelDivision, name: generateName(5)).save(flush: true)
            aState.children.add(localityDivision)
            localityDivision.localityParent = aState
            populateDivision(localityDivision)
        }
    }

    def populateDivision(Locality aDivision)
    {
        aDivision.children = new ArrayList<Locality>()
        Locality localityVillage
        for (int i = 0; i < 2; i++)
        {
            localityVillage = new Locality(level: levelVillage, name: generateName(5)).save(flush: true)
            aDivision.children.add(localityVillage)
            localityVillage.localityParent = aDivision
        }
    }


    public String generateName(int length)
    {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String name = "";
        for (int x = 0; x < length; x++)
        {
            int i = (int) Math.floor(Math.random() * 26);
            name += chars.charAt(i);
        }
        System.out.println(name);
        return name;
    }

    def index()
    {
        redirect(action: "list", params: params)
    }

    def list(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        [localityInstanceList: Locality.list(params), localityInstanceTotal: Locality.count()]
    }

    def create()
    {
        [localityInstance: new Locality(params)]
    }

    def save()
    {
        def localityInstance = new Locality(params)

        if (!localityInstance.save(flush: true))
        {
            render(view: "create", model: [localityInstance: localityInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'locality.label', default: 'Locality'), localityInstance.id])
        redirect(action: "show", id: localityInstance.id)
    }

    def show(Long id)
    {
        def localityInstance = Locality.get(id)
        if (!localityInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'locality.label', default: 'Locality'), id])
            redirect(action: "list")
            return
        }

        [localityInstance: localityInstance]
    }

    def edit(Long id)
    {
        def localityInstance = Locality.get(id)
        if (!localityInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'locality.label', default: 'Locality'), id])
            redirect(action: "list")
            return
        }

        [localityInstance: localityInstance]
    }

    def update(Long id, Long version)
    {
        def localityInstance = Locality.get(id)
        if (!localityInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'locality.label', default: 'Locality'), id])
            redirect(action: "list")
            return
        }

        if (version != null)
        {
            if (localityInstance.version > version)
            {
                localityInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'locality.label', default: 'Locality')] as Object[],
                        "Another user has updated this Locality while you were editing")
                render(view: "edit", model: [localityInstance: localityInstance])
                return
            }
        }

        localityInstance.properties = params

        if (!localityInstance.save(flush: true))
        {
            render(view: "edit", model: [localityInstance: localityInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'locality.label', default: 'Locality'), localityInstance.id])
        redirect(action: "show", id: localityInstance.id)
    }

    def delete(Long id)
    {
        def localityInstance = Locality.get(id)
        if (!localityInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'locality.label', default: 'Locality'), id])
            redirect(action: "list")
            return
        }

        try
        {
            localityInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'locality.label', default: 'Locality'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e)
        {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'locality.label', default: 'Locality'), id])
            redirect(action: "show", id: id)
        }
    }
}
